package com.android.functionmanagement.mediarecorder;

import android.media.MediaRecorder;
import java.io.File;
import java.io.IOException;

import com.android.functionmanagement.globle.LogGloble;

public class Recorder extends MediaRecorder implements
		android.media.MediaRecorder.OnErrorListener {

	private static final String TAG = "Recorder";
	private MediaRecorder mRecorder = null;
	private String mCurrentFilePath = null;

	/**
	 * M: set the path of audio file which will Recorder
	 * 
	 * @param filePath
	 */
	public void setCurrentFilePath(String filePath) {
		mCurrentFilePath = filePath;
	}

	/**
	 * M: start Recorder the audio file which is set in setCurrentFilePath
	 * 
	 * @return the result of play back, success or fail
	 */
	public boolean startPlayback() {
		if (null == mCurrentFilePath) {
			return false;
		}
		File file = new File(mCurrentFilePath);
		if (!file.exists()) {
			return false;
		}
		synchronized (this) {
			if (null == mRecorder) {
				mRecorder = new MediaRecorder();
				try {
					mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
					mRecorder
							.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
					mRecorder
							.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
					mRecorder.setOutputFile(mCurrentFilePath);
					mRecorder.setOnErrorListener(this);
					mRecorder.prepare();
					mRecorder.start();
				} catch (IllegalStateException e) {
					return handleException(e);
				} catch (IOException e) {
					return handleException(e);
				}
			}
		}
		return true;
	}

	/**
	 * M: Handle the Exception when call the function of MediaRecorder
	 * 
	 * @return false
	 */
	public boolean handleException(Exception exception) {
		LogGloble.i(TAG, "<handleException>");
		exception.printStackTrace();
		if (mRecorder != null) {
			mRecorder.release();
			mRecorder = null;
		}
		return false;
	}

	/**
	 * M: goon Recorder the audio file which is set in setCurrentFilePath
	 */
	public boolean goonRecorderback() {
		if (null == mRecorder) {
			return false;
		}

		try {
			mRecorder.start();
		} catch (IllegalStateException e) {
			return handleException(e);
		}
		return true;
	}

	/**
	 * M: stop Recorder the audio file which is set in setCurrentFilePath
	 */
	public boolean stopRecorderback() {
		// we were not in playback
		synchronized (this) {
			if (null == mRecorder) {
				return false;
			}
			try {
				mRecorder.stop();
			} catch (IllegalStateException e) {
				return handleException(e);
			}
			mRecorder.release();
			mRecorder = null;
		}
		return true;
	}

	/**
	 * M: reset Recorder to initial state
	 */
	public void reset() {
		synchronized (this) {
			if (null != mRecorder) {
				mRecorder.stop();
				mRecorder.release();
				mRecorder = null;
			}
		}
		mCurrentFilePath = null;
	}

	@Override
	public void onError(MediaRecorder arg0, int arg1, int arg2) {
		reset();
	}

}
